package com.huanrong.controller;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HelloController
{
    private static final Logger logger = Logger.getLogger(HelloController.class);
    
    @Autowired
    private SecurityManager securityManager;
    
    @PostConstruct
    public void init()
    {
        SecurityUtils.setSecurityManager(securityManager);
    }
    
    @RequiresPermissions(value = {"test"})
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String test(HttpServletRequest request, Model model)
    {
        model.addAttribute("name", "卢丛越");
        return "test";
    }
    
    @GetMapping(value = "/login")
    public String loginView(HttpServletRequest request)
    {
        return "login";
    }
    
    @PostMapping(value = "/login")
    public String login(HttpServletRequest request)
    {
        logger.info("用户登录：" + request.getParameter("name"));
        
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token =
            new UsernamePasswordToken(request.getParameter("name"), request.getParameter("password"));
        try
        {
            securityManager.login(subject, token);
        }
        catch (AuthenticationException e)
        {
            return "login";
        }
        return "welcome";
    }
}
